import BDKit
import ProgressHUD
import UIKit

class KeyboardViewController: UIViewController {

  private var lastKeyboardEnabledState: Bool?

  let taskId: Int

  init(taskId: Int) {
    self.taskId = taskId
    super.init(nibName: nil, bundle: nil)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  private let scrollView = UIScrollView()
  private let contentView = UIStackView()
  private let settingsView = SettingsView()
  private let liveCardView = LiveCardView()
  private let materialView = MaterialView()

  private var materialBottomConstraint: NSLayoutConstraint?
  private var materialTableViewHeightConstraint: NSLayoutConstraint?

  private var dataSource: [ShareMaterial] = []

  override func viewDidLoad() {
    super.viewDidLoad()

    setupUI()
    setupActions()
    loadMaterialCategory()
    loadData()
    appDidBecomeActive()
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(appDidBecomeActive),
      name: UIApplication.didBecomeActiveNotification,
      object: nil)
  }

  let mobPageName = "app-键盘"
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    MobClick.beginLogPageView(mobPageName)
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    MobClick.endLogPageView(mobPageName)
  }

  @objc private func appDidBecomeActive() {
    print("App 回到前台")
    let isKeyboardEnabled = UITextInputMode.activeInputModes.contains {
      guard let identifier = $0.value(forKey: "identifier") as? String else { return false }
        return identifier.contains(BaoDanConstants.keyboardBundleIdentifier)
    }
    let stateChanged = lastKeyboardEnabledState != isKeyboardEnabled
    lastKeyboardEnabledState = isKeyboardEnabled
    if stateChanged {
      self.scrollView.setContentOffset(.zero, animated: true)
    }
    if isKeyboardEnabled {
      settingsView.removeFromSuperview()
      materialTableViewHeightConstraint?.isActive = false
      materialBottomConstraint = self.materialView.bottomAnchor.constraint(
        equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -16)
      materialBottomConstraint?.isActive = true
      scrollView.isScrollEnabled = false
      materialTableViewHeightConstraint?.constant = 500
    } else {
      contentView.insertArrangedSubview(self.settingsView, at: 0)
      materialTableViewHeightConstraint?.isActive = true
      materialBottomConstraint?.isActive = false
      scrollView.isScrollEnabled = true
    }
    view.layoutIfNeeded()
  }

  private func setupUI() {
    view.backgroundColor = UIColor(hex: "#F6F6F8")
    navigationItem.title = "爆单键盘"
    //        navigationController?.navigationBar.prefersLargeTitles = true
    //        navigationItem.largeTitleDisplayMode = .always

    scrollView.translatesAutoresizingMaskIntoConstraints = false
    contentView.translatesAutoresizingMaskIntoConstraints = false
    contentView.axis = .vertical
    contentView.spacing = 12

    contentView.isLayoutMarginsRelativeArrangement = true
    contentView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 20, right: 20)

    settingsView.translatesAutoresizingMaskIntoConstraints = false
    liveCardView.translatesAutoresizingMaskIntoConstraints = false
    materialView.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(scrollView)
    scrollView.addSubview(contentView)

    [settingsView, liveCardView, materialView].forEach {
      contentView.addArrangedSubview($0)
    }

    NSLayoutConstraint.activate([
      scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
      scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
      scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
      scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),

      contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
      contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
      contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
      contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
      contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),

      liveCardView.heightAnchor.constraint(equalToConstant: 72),
    ])

    let tableHeight = UIScreen.main.bounds.size.height * 0.5
    materialTableViewHeightConstraint = materialView.tableView.heightAnchor.constraint(
      equalToConstant: tableHeight)
    materialTableViewHeightConstraint?.isActive = true
  }

  private func setupActions() {
    settingsView.settingsButton.addTarget(
      self, action: #selector(openSettings), for: .touchUpInside)
    materialView.segmentedControl.addTarget(
      self, action: #selector(segmentChanged(_:)), for: .valueChanged)

    materialView.tableView.dataSource = self
  }

  var materialCategorys: [Category] = []
  private func loadMaterialCategory() {
    HttpClient.shared.postWithAutoHUD(endpoint: "/material/category/list", body: [:]) {
      [weak self] (categorys: [Category]?) in
      guard let self = self else { return }
      guard let categorys = categorys else { return }
      materialCategorys = categorys
      materialView.configSegment(data: categorys)
    }
  }

  private func loadData() {
    HttpClient.shared.postWithAutoHUD(endpoint: "/latestLiveInfo", body: ["taskId": taskId]) {
      [weak self] (data: LiveData?) in
      guard let self = self else { return }
      guard let data = data else { return }
      liveCardView.configUI(data: data)
    }
  }

  private func loadMaterials(categoryId: Int = -1) {
    print("loadMaterials")
    HttpClient.shared.postWithAutoHUD(
      endpoint: "/material/list", body: ["taskId": taskId, "categoryId": categoryId]
    ) { [weak self] (data: [ShareMaterial]?) in
      guard let self = self else { return }
      guard let data = data else { return }
      self.dataSource = data
      self.materialView.tableView.reloadData()
    }
  }

  @objc private func openSettings() {
    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return }
    UIApplication.shared.open(settingsUrl)
  }

  @objc private func segmentChanged(_ sender: UISegmentedControl) {
    print("Segment changed to \(sender.selectedSegmentIndex)")
    // 这里可以根据 segment 改变 dataSource 然后 reload table
    let selectedIndex = sender.selectedSegmentIndex
    if let title = sender.titleForSegment(at: selectedIndex),
      let category = materialCategorys.first(where: { $0.name == title })
    {
      loadMaterials(categoryId: category.id)
    }
  }
}

extension KeyboardViewController: UITableViewDataSource, UITableViewDelegate {

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataSource.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell =
      tableView.dequeueReusableCell(withIdentifier: "KeyboardMaterialCell", for: indexPath)
      as! ShareCell
    let data = dataSource[indexPath.row]
    cell.configUI(data: data)

    cell.onShareButtonTapped = { [weak self] in
      guard let self = self else { return }
      // 纯文本入剪切板
      if data.materialType == 1 {
        UIPasteboard.general.string = data.cardTitle ?? data.text.first ?? "爆单键盘"
        //                ProgressHUD.queueSucceed("文案已复制，分享时直接粘贴发送", duration: 2)
        ProgressHUD.succeed("文案已复制，分享时直接粘贴发送")
        return
      }
      // 有图片去微信分享
      self.shareMaterial(data)
    }
    return cell
  }

}

struct ShareMaterialModel: Codable {
  let imgUrl: String?
}

extension KeyboardViewController {
  func shareMaterial(_ data: ShareMaterial) {
    let body =
      [
        "taskId": self.taskId,
        "categoryId": data.categoryId,
        "materialId": data.materialId,
      ] as [String: Any]
    ProgressHUD.animate("下载图片中...", interaction: false)
    //        ProgressHUD.queueAnimate("下载图片中...", duration: 999)

    HttpClient.shared.postWithAutoHUD(endpoint: "/material/share", body: body) {
      (result: ShareMaterialModel?) in
      let shareModel = WXShareModel(
        text: data.cardTitle ?? data.text.first ?? "爆单键盘", imagePath: result?.imgUrl,
        entranceMiniProgramUsername: nil, entranceMiniProgramPath: nil, webpageUrl: nil,
        miniprogramType: nil, withShareTicket: nil)
      ProgressHUDQueue.shared.dismiss()
      WXApi.shareAction(share: shareModel)
    }
  }
}
